iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
類型 說明 檔案位置
單元測試 測試單一函式/模組邏輯 mod tests {} 內嵌在模組中
整合測試 模擬外部使用情境 tests/ 目錄下
範例測試 測試 doc code examples /// 註解中寫 code

單元測試 (Unit Test)

// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
}
  • #[cfg(test)]:只在測試時編譯。
  • #[test]:標記為測試函數。
  • assert_eq!:驗證輸出與預期相符。

** 整合測試 (Integration Test)**

建立 tests/ 目錄:

mkdir tests
// tests/integration_test.rs
use my_crate::add;

#[test]
fn test_add_integration() {
    assert_eq!(add(10, 5), 15);
}

注意:

  • my_crate 是 Cargo.toml 中的 package 名稱。
  • 每個 .rs 檔案會被當成一個 crate 來執行。

範例測試 (Doc Test)

/// Adds two numbers.
/// ```
/// use my_crate::add;
/// assert_eq!(add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

cargo test 會自動執行文件中所有 /// 包含的測試程式碼。


執行測試

cargo test             # 執行所有測試
cargo test test_add    # 執行指定測試
cargo test -- --nocapture  # 顯示 println! 輸出

常見斷言

assert!(cond);               // 為 true
assert_eq!(a, b);            // 相等
assert_ne!(a, b);            // 不相等
assert!(result.is_ok());     // Result::Ok
assert!(result.is_err());    // Result::Err

非同步測試(async)

# Cargo.toml
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
#[tokio::test]
async fn test_async_logic() {
    let result = async_fn().await;
    assert_eq!(result, 42);
}

先放上


上一篇
【Day13】- Rust(專案管理)
下一篇
【Day15】- NautilusTrader 如何結合 Rust 和 Python
系列文
NautilusTrader 架構解析:Rust 在高效能量化交易平台中的角色與優勢22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言